package com.chenzehe.alimama.html;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class BasePage implements IPage {
	protected Logger log = LoggerFactory.getLogger(getClass());
	protected static final int DEFAULT_TIMEOUT_IN_SECONDS = 300;
	private final WebDriver webDriver;

	public BasePage(WebDriver webDriver) {
		if (webDriver != null) {
			this.webDriver = webDriver;
			RuntimeWebDriver.setRuntimeWebDriver(webDriver);
		} else {
			this.webDriver = RuntimeWebDriver.getRuntimeWebDriver();
		}
	}

	public WebDriver getWebDriver() {
		return webDriver;
	}

	public void waitForNavigateTo(final String url) {
		WebDriverWait waiter = new WebDriverWait(getWebDriver(),
				DEFAULT_TIMEOUT_IN_SECONDS);
		waiter.until(new ExpectedCondition<Boolean>() {
			@Override
			public Boolean apply(WebDriver d) {
				return d.getCurrentUrl().contains(url);
			}
		});
	}

	/**
	 * 输入框输入 先删除内容，然后输入
	 * 
	 * @param inputElement
	 *            输入框
	 * @param value
	 *            要输入的文本
	 */
	protected void clearAndSendKeys(WebElement inputElement, String value) {
		inputElement.clear();
		inputElement.sendKeys(value);
	}

	/**
	 * 跳转到目标url
	 */
	public void navigate(String url) {
		log.info("navigate to page:" + url);
		getWebDriver().navigate().to(url);
		waitForNavigateTo(url);
	}
}
